//
//  SchoolRootNewsViewController.swift
//  KaMengApplication
//
//  Created by DUONIU_MAC on 2018/10/22.
//  Copyright © 2018年 DUONIU_MAC. All rights reserved.
//

import UIKit
import XLPagerTabStrip

class SchoolRootNewsViewController: KMViewController {
    
    fileprivate let cellId = "schoolCell"
    
    fileprivate var dataArray = [SchoolNewsModel]()
    
    fileprivate var collectionView : UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        createCollectionView()
        
    }
    
    //MARK: 创建tableView
    fileprivate func createCollectionView() {
        
        //读取缓存的学堂新闻
        if self.dataArray.count == 0 {
            if NSKeyedUnarchiver.unarchiveObject(withFile: schoolNewsData) != nil {
                
                self.dataArray = NSKeyedUnarchiver.unarchiveObject(withFile: schoolNewsData) as! [SchoolNewsModel]
            }
        }
        
        let layout = UICollectionViewFlowLayout()
        layout.sectionInset = .init(top: RATIO_H(maxNum: 20), left: RATIO(maxNum: 20), bottom: RATIO(maxNum: 20), right: RATIO_H(maxNum: 20))
        layout.itemSize = .init(width: (ScreenW-RATIO(maxNum: 60))/2, height: RATIO_H(maxNum: 180))
        
        collectionView = UICollectionView.init(frame: .zero, collectionViewLayout: layout)
        collectionView.backgroundColor = UIColor.mineColor()
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(SchoolNewsCell.self, forCellWithReuseIdentifier: cellId)
        self.view.addSubview(collectionView)
        
        collectionView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.zero)
        }
        
        
        KMTool.setRefresh(with: collectionView, headerAction: {[weak self] in
            
            self?.getData()
        }, footerAction: nil)
        
        self.collectionView.mj_header.beginRefreshing()
    }
    
    //MARK: 获取数据
    fileprivate func getData() {
        
        KMTool.requestGetData(URLString: url_schoolNews, parameters: nil, success: { (data) in
            
                self.collectionView.mj_header.endRefreshing()
            
            let elements = ["//a[@class='aa']","//a[@class='aa']/img","//a[@class='aa']/h3",]
            let attributes = ["href","src","text"]
            let keys = ["href","image","title"]
            
            let array = KMTool.htmlToModel(data: data, elements: elements, attributes: attributes, keys: keys)
            
            if array.count > 0 {
                self.dataArray.removeAll()
            }else{
                return
            }
            
            for item in array {
                let model = SchoolNewsModel.setModel(with: item)
                self.dataArray.append(model)
            }
            
            //缓存学堂新闻
            NSKeyedArchiver.archiveRootObject(self.dataArray, toFile: schoolNewsData)
            
            self.collectionView.reloadData()
            
        }) {
                self.collectionView.mj_header.endRefreshing()
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        

    }
    

    

}

extension SchoolRootNewsViewController : UICollectionViewDelegate,UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return dataArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as? SchoolNewsCell
        cell?.model = dataArray[indexPath.row]
        return cell!
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        collectionView.deselectItem(at: indexPath, animated: true)
        
        let model = dataArray[indexPath.row]
        
        if indexPath.row > 13 {
            
            let webVC = SchoolWebViewController.init(urlString: kmHttps + model.href!,title:model.title)
            webVC.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(webVC, animated: true)
        }else{
            
            let schoolDetailsVC = SchoolDetailsViewController.init(title: model.title, urlString: kmHttps + model.href!,schoolId:"\(indexPath.row+1)")
            schoolDetailsVC.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(schoolDetailsVC, animated: true)
        }
    }
    
}
